<?php

namespace App\Console\Commands;

use App\LiveUser;
use App\User;
use App\Usermeta;
use App\Live;
use Illuminate\Console\Command;

class SwooleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start Swoole WebSocket';
    protected $env;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->env = new \swoole_websocket_server("0.0.0.0", 9501);

//        $this->env->on('open', function (\swoole_websocket_server $server, $request) {
//            echo "server: handshake success with fd{$request->fd},\n";
//        });

        $this->env->on('message', function (\swoole_websocket_server $server, $frame) {
//            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
//            $server->push($frame->fd, "this is server");
            $data = json_decode($frame->data);
            switch ($data->webType){
                case 'login':
                    $User = User::where("session",$data->session)->first();
                    if($User&&$User->id==$data->uid){
                        $LiveUser = LiveUser::where("user_id",$User->id)->where("parent_id",$data->id)->first();
                        if(!$LiveUser){
                            $LiveUser = new LiveUser();
                            $LiveUser->user_id = $User->id;
                            $LiveUser->parent_id = $data->id;
                        }
                        $LiveUser->fd = $frame->fd;
                        if($LiveUser->save()){
                            $avatar = Usermeta::where("user_id",$User->id)->where("key","avatar")->first();
                            $this->Push_msg($server,$data->id,'{"type":"user","msg":{"id":'.$LiveUser->id.',"user_id":'.$User->id.',"name":"'.$User->name.'","avatar":"'.$avatar->value.'"}}');

                            $LiveUsers = LiveUser::where("parent_id",$data->id)->get();
                            $Users = [];
                            foreach ($LiveUsers as $u){
                                if($u->user_id != $User->id){
                                    $_avatar = Usermeta::where("user_id",$u->user_id)->where("key","avatar")->first();
                                    $user = User::find($u->user_id);
                                    $img = $_avatar?$_avatar->value:"https://sichuangyi.demopp.in/upload/avatar/avatar.png";
                                    $_u = Array("id"=>$u->id,"user_id"=>$u->user_id,"name"=>$user->name,"avatar"=>$img);
                                }else{
                                    $_u = Array("id"=>$u->id,"user_id"=>$u->user_id,"name"=>$User->name,"avatar"=>$avatar->value);
                                }
                                array_push($Users,$_u);
                            }
                            $Lives = Live::where("parent_id",$data->id)->select('id','user_id','type','content','more','created_at')->get();
                            $_data = Array("type"=>"init","userList"=>$Users,"list"=>$Lives);
                            $server->push($frame->fd, json_encode($_data, JSON_UNESCAPED_UNICODE));
                        }
                    }
                    break;
                case 'msg':
                    $live = new Live();
                    $live->user_id = $data->user_id;
                    $live->type = $data->type;
                    $live->content = $data->content;
                    $live->parent_id = $data->id;
                    $live->more = $data->more;
                    if($live->save()){
                        $this->Push_msg($server,$data->id,'{"type":"msg","msg":{"id":'.$live->id.',"user_id":'.$data->user_id.',"type":"'.$data->type.'","content":"'.$data->content.'","more":"'.$data->more.'","created_at":"'.$live->created_at.'"}}');
                    }
                    break;
                default:
                    break;
            }
        });

        $this->env->on('close', function ($ser, $fd) {
            $LiveUser = LiveUser::where("fd",$fd)->first();
            if($LiveUser){
                $LiveUser->fd = 0;
                $LiveUser->save();
            }
        });

        $this->env->start();
    }
    private function Push_msg($ser,$id,$msg){
        $Users = LiveUser::where("parent_id",$id)->where("fd",">",0)->select('fd')->get();
        foreach ($Users as $u){
            $ser->push($u->fd, $msg);
        }
    }
}
